package com.xydtech.ecard.ecard.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.xydtech.common.core.domain.entity.SysDept;
import com.xydtech.common.enums.ResultStatus;
import com.xydtech.common.exception.ApiException;
import com.xydtech.common.model.ResponseModel;
import com.xydtech.common.utils.StringUtils;
import com.xydtech.ecard.busi.domain.EcardApiEcardBusiReservation;
import com.xydtech.ecard.busi.service.IEcardApiEcardBusiReservationService;
import com.xydtech.ecard.ecard.service.EcardApiWeiZongService;
import com.xydtech.ecard.user.domain.EcardApiUserInfo;
import com.xydtech.ecard.user.service.IEcardApiUserService;
import com.xydtech.system.domain.SysWechatApplet;
import com.xydtech.system.service.ISysDeptService;
import com.xydtech.system.service.ISysWechatAppletService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.HashMap;
import java.util.Map;

/**
 * 电子名片-微众税务接口类
 *
 * @author yjs
 * @date 2022/7/29 11:27
 */

@Controller
@Api(tags = "电子名片-微众税务接口")
@RequestMapping("/ecardSaasApi/weiZhongApi")
public class EcardApiWeiZhongController extends EcardApiBaseController {
    @Autowired
    private EcardApiWeiZongService apiWeiZongService;
    @Autowired
    private ISysWechatAppletService wechatAppletService;
    @Autowired
    private IEcardApiUserService ecardApiUserService;
    @Autowired
    private IEcardApiEcardBusiReservationService ecardApiEcardBusiReservationService;
    @Autowired
    private ISysDeptService sysDeptService;
    /**
     * 获取商易通企业认证授权链接
     *
     * @author yjs
     * @date 2022/7/28 10:48
     */

    @GetMapping(value = "/goAuthorizeUrl")
    @ApiOperation(value = "电子名片-获取认证授权链接", notes = "电子名片-获取认证授权链接")
    @ResponseBody
    public ResponseModel goAuthorizeUrl(@RequestParam(required = false) String proCode, @RequestParam(required = false) String cityCode) {
        try {
            String salt = getSalt();//盐值
            String currentUserId = getCurrentUserId();
            EcardApiUserInfo userInfo = ecardApiUserService.getUserInfo(currentUserId, salt);
            SysDept dept = sysDeptService.selectSecondLevelDeptByDeptId(userInfo.getDeptId());
            //当前小程序id
            SysWechatApplet wechatApplet = getAppIdByDeptId(userInfo.getDeptId());
            String appId = wechatApplet.getAppid();
            if (StringUtils.isEmpty(appId) && StringUtils.isEmpty(proCode) && StringUtils.isEmpty(cityCode)) {
                return ResponseModel.error(ResultStatus.PARAMETER_ERROR);
            }
            Map<String, Object> paramMap = new HashMap<>();
            paramMap.put("appId", appId);
            //认证省级编码
            paramMap.put("proCode", proCode.substring(0, 6));
            //认证地区的市级编码
            paramMap.put("cityCode", cityCode.substring(0, 6));
            //回调地址
            paramMap.put("redirectUri", "/pages/index/index?wztype=applet");
            //机构id
            paramMap.put("deptId", dept.getDeptId());
            ResponseModel map = apiWeiZongService.goAuthorize(paramMap);
            JSONObject reportInfoObj = JSONObject.parseObject(JSON.toJSONString(map.getData()));
            return ResponseModel.ok(reportInfoObj);
        } catch (ApiException ex) {
            return ResponseModel.error(ex);
        } catch (Exception ex) {
            return ResponseModel.error(ex, this.getClass(), this.getClass().getSimpleName() + "------->" + new Exception().getStackTrace()[0].getMethodName());
        }
    }

    /**
     * 获取商易通企业认证授权信息
     *
     * @author yjs
     * @date 2022/7/28 10:48
     */

    @GetMapping(value = "/getAuthorizeInfo")
    @ApiOperation(value = "电子名片-获取认证授权信息", notes = "电子名片-获取认证授权信息")
    @ResponseBody
    public ResponseModel getAuthorizeInfo(@RequestParam(required = false) String resId) {
        try {
            String salt = getSalt();//盐值
            String currentUserId = getCurrentUserId();
            EcardApiUserInfo userInfo = ecardApiUserService.getUserInfo(currentUserId, salt);
            //当前小程序id
            SysWechatApplet wechatApplet = getAppIdByDeptId(userInfo.getDeptId());
            String appId = wechatApplet.getAppid();
            SysDept dept = sysDeptService.selectSecondLevelDeptByDeptId(userInfo.getDeptId());
            if (StringUtils.isEmpty(appId) && StringUtils.isEmpty(resId)) {
                return ResponseModel.error(ResultStatus.PARAMETER_ERROR);
            }
            Map<String, Object> paramMap = new HashMap<>();
            paramMap.put("appId", appId);
            //预约编号
            paramMap.put("resId", resId);
            //机构id
            paramMap.put("deptId", dept.getDeptId());
            ResponseModel map = apiWeiZongService.getAuthorizeInfo(paramMap, salt);
            JSONObject reportInfoObj = JSONObject.parseObject(JSON.toJSONString(map.getData()));
            return ResponseModel.ok(reportInfoObj);
        } catch (ApiException ex) {
            return ResponseModel.error(ex);
        } catch (Exception ex) {
            return ResponseModel.error(ex, this.getClass(), this.getClass().getSimpleName() + "------->" + new Exception().getStackTrace()[0].getMethodName());
        }
    }

    /**
     * 获取商易通企业税务报告
     *
     * @author yjs
     * @date 2022/7/28 10:48
     */
    @GetMapping(value = "/getReportInfo")
    @ApiOperation(value = "电子名片-获取企业税务报告", notes = "电子名片-获取企业税务报告")
    @ResponseBody
    public ResponseModel getReportInfo(@RequestParam(required = false) String resId, @RequestParam(required = false) String reportType) {
        try {
            String salt = getSalt();//盐值
            String currentUserId = getCurrentUserId();
            EcardApiUserInfo userInfo = ecardApiUserService.getUserInfo(currentUserId, salt);
            //当前小程序id
            SysWechatApplet wechatApplet = getAppIdByDeptId(userInfo.getDeptId());
            String appId = wechatApplet.getAppid();
            if (StringUtils.isEmpty(appId) && StringUtils.isEmpty(resId) && StringUtils.isEmpty(reportType)) {
                return ResponseModel.error(ResultStatus.PARAMETER_ERROR);
            }
            //当前小程序对应的法人机构ID
            Long parentDeptId = wechatApplet.getDeptId();

            //获取当前用户的信息
            Map<String, Object> paramMap = new HashMap<>();
            paramMap.put("appId", appId);
            //预约编号
            paramMap.put("resId", resId);
            //税务报告类型，01企业交易分析报告，02企业财税分析报告
            paramMap.put("reportType", reportType);
            paramMap.put("deptId", parentDeptId);
            //处理文件返回路径
            JSONObject jsonUrl = apiWeiZongService.getReportInfo(paramMap, salt);
            //PDF文件路径
            String pdfUrl = jsonUrl.getString("newPdfFile");
            //图片路径
            String imgUrl = jsonUrl.getString("viewPath");
            //更新业务预约登记数据
            EcardApiEcardBusiReservation ecardBusiReservation = new EcardApiEcardBusiReservation();
            ecardBusiReservation.setResId(Long.valueOf(resId));
            imgUrl.replace("png", "pdf");
            String pdfKey = "";
            if ("01".equals(reportType)) {
                ecardBusiReservation.setTransReportUrl(imgUrl);
                pdfKey = "$.transReportUrl";
            } else {
                ecardBusiReservation.setTaxReportUrl(imgUrl);
                pdfKey = "$.taxReportUrl";
            }
            int updateCount = ecardApiEcardBusiReservationService.updateEcardApiEcardBusiReservation(ecardBusiReservation, salt);
            ecardApiEcardBusiReservationService.updatePdfReport(pdfKey, pdfUrl, resId);
            return updateCount > 0 ? ResponseModel.ok(imgUrl) : ResponseModel.error("查询报告失败!");
        } catch (ApiException ex) {
            return ResponseModel.error(ex);
        } catch (Exception ex) {
            return ResponseModel.error(ex, this.getClass(), this.getClass().getSimpleName() + "------->" + new Exception().getStackTrace()[0].getMethodName());
        }
    }
}
